package com.pine.app.module.security.core.web;


import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Web线程拦截器，用于统一处理线程变量
 *      该过滤器执行顺序早于springsecurity的过滤器
 *
 * @author <a href="mailto:shangzhi.ibyte@gmail.com">iByte</a>
 * @Date: 2019-10-11
 */
public class WebThreadFilter extends CompositeFilterProxy {

    /**
     * 应用上下文
     */
    private ApplicationContext applicationContext;
    /**
     * 带参数构造器
     *
     * @param filterDefs
     */
    public WebThreadFilter(List<IWebFilterDef> filterDefs) {
        super(filterDefs);
    }

    @Override
    protected void initFilterBean() throws ServletException {
        applicationContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
        super.initFilterBean();
    }

    @Override
    protected void handleInnerFilters(List<Filter> innerFilters) {
        super.handleInnerFilters(innerFilters);
       Map<String,BaseWebFilter> map = applicationContext.getBeansOfType(BaseWebFilter.class);
       if(map!=null&&map.size()>0){
           innerFilters.addAll(new ArrayList<>( map.values()));
       }
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain chain) throws ServletException, IOException {
            compositeFilter.doFilter(request, response, chain);
        }
}

